<template>
  <div class="container">
    <div class="up-container">
      <el-form :model="queryParams" ref="airSpaceRef" :rules="queryRules">
        <div class="basic-container">
          <div class="title">
            <img src="@/assets/images/airplane.png" alt="" />
            <span>{{ $t('airspaceAdd.basicInfo') }}</span>
          </div>
          <el-form-item :label="$t('airspaceAdd.airspaceName')" prop="airspaceName">
            <el-input
                v-model="queryParams.airspaceName"
                :placeholder="$t('airspaceAdd.dimensionName')"
                clearable
                maxlength="20"
                :disabled="enterType"
            />
          </el-form-item>
          <el-form-item :label="$t('airspaceAdd.airspaceType')" prop="airTypeId">
            <el-select v-model="queryParams.airTypeId" :disabled="enterType" @change="getairTypeContent" :placeholder="$t('airspaceAdd.dimensionType')" clearable >
              <el-option
                  v-for="dict in airspaceTypeList"
                  :key="dict.airTypeId"
                  :label="dict.airTypeName"
                  :value="dict.airTypeId"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('airspaceAdd.AirspaceBottomHeight') + '：' " prop="lowHeight">
            <el-input
                v-model="queryParams.lowHeight"
                :placeholder="$t('airspaceAdd.lowCheck')"
                clearable
                :disabled="enterType"
            />
          </el-form-item>
          <el-form-item :label="$t('airspaceAdd.AirspaceCeilingHeight') + '：'" prop="topHeight">
            <el-input
                v-model="queryParams.topHeight"
                :placeholder="$t('airspaceAdd.topCheck')"
                clearable
                :disabled="enterType"
            />
          </el-form-item>
          <el-form-item :label="$t('airspaceAdd.startTime')" prop="airSpaceStartTime">
            <el-date-picker
                v-model="queryParams.airSpaceStartTime"
                type="datetime"
                format="YYYY-MM-DD HH:mm"
                date-format="YYYY/MM/DD ddd"
                time-format="A hh:mm"
                :placeholder="$t('airspaceAdd.dimensionStartTime')"
                @change="startTimeHandle"
                :disabled="enterType"
            />
          </el-form-item>
          <el-form-item :label="$t('airspaceAdd.endTime')" prop="endTime">
            <el-date-picker
                v-model="queryParams.endTime"
                type="datetime"
                format="YYYY-MM-DD HH:mm"
                date-format="YYYY/MM/DD ddd"
                time-format="A hh:mm"
                :placeholder="$t('airspaceAdd.dimensionEndTime')"
                @change="endTimeHandle"
                :default-time="defaultTime"
                :disabled="enterType || disVisible"
            />
            <div class="permanent" @click="radioHandle">
              <div>
                <div class="permanentRadio" v-if="radioVisible"></div>
                <div class="permanentRadio2" v-else></div>
              </div>
              <div>{{ $t('airspaceAdd.permanentValidity') }}</div>
            </div>
          </el-form-item>
          <el-form-item :label="$t('airspaceAdd.airspaceStatus')" prop="airspaceStatus">
            <el-select v-model="queryParams.airspaceStatus" :disabled="enterType" :placeholder="$t('airspaceAdd.dimensionAirspaceStatus')" clearable @change="dialogVisibleChange">
              <el-option
                  v-for="dict in airSpaceStatusList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('airspaceAdd.relevantDocuments')" prop="files">
            <Upload
                :fileList="queryParams.files"
                :isCanDelete="!enterType"
                :showButton="!enterType"
                :isFull="true"
                @success="uploadSuccess"
                @deleteFile="uploadRemove"
            />
          </el-form-item>
          <el-form-item :label="$t('airspaceAdd.remark')">
            <el-input v-model="queryParams.remark" :placeholder="$t('airspaceAdd.dimensionRemark')" :disabled="enterType" show-word-limit style="height: 100px" maxlength="150" :rows="3" type="textarea" />
          </el-form-item>
        </div>
        <div class="draw-container">
          <div class="range">
            <div class="title">
              <img src="@/assets/images/airplane.png" alt="" />
              <span>{{ $t('airspaceAdd.drawAirspaceRange') }}</span>
            </div>
            <el-form-item :label="$t('airspaceAdd.drawAirspaceRange')" prop="resource"  v-if="!enterType">
              <el-radio-group v-model="queryParams.resource" @change="resourceChange">
                <el-radio :label="$t('airspaceAdd.circle')" />
                <el-radio :label="$t('airspaceAdd.polygon')" />
                <el-radio :label="$t('airspaceAdd.reset')" />
              </el-radio-group>
            </el-form-item>
          </div>
          <div id="airspaceMap"></div>
          <!--  地址搜索  -->
          <div id="myPageTop">
            <input id="tipinput" :placeholder="$t('airspaceAdd.enterAddress')" />
            <el-button :icon="Search" @click="mapSelect">{{ $t('airspaceAdd.search') }}</el-button>
          </div>
          <!--  图层控件  -->
          <div id="airspaceControl" :class="circleVisible || polygonVisible ? 'airspaceLayer' : 'airspaceLayer-down'" @click="airspaceControl" @mouseover="airspaceMouseover"></div>
          <div class="circleDraw" v-if="!enterType && circleVisible">
            <div>{{ $t('airspaceAdd.circleDraw') }}</div>
            <div>{{ $t('airspaceAdd.circleStep1') }}</div>
            <div>{{ $t('airspaceAdd.circleStep2') }}</div>
            <div>{{ $t('airspaceAdd.circleStep3') }}</div>
            <div>{{ $t('airspaceAdd.circleStep4') }}</div>
          </div>
          <div class="polygonDraw" v-if="!enterType && polygonVisible">
            <div>{{ $t('airspaceAdd.polygonDraw') }}</div>
            <div>{{ $t('airspaceAdd.polygonStep1') }}</div>
            <div>{{ $t('airspaceAdd.polygonStep2') }}</div>
            <div>{{ $t('airspaceAdd.polygonStep3') }}</div>
            <div>{{ $t('airspaceAdd.polygonStep4') }}</div>
            <div>{{ $t('airspaceAdd.polygonStep5') }}</div>
          </div>
        </div>
      </el-form>

    </div>

    <div class="down-container">
      <div v-if="!enterType">
        <el-button class="btn delete" @click="goBack">{{ $t('airspaceAdd.cancellation') }}</el-button>
        <el-button class="btn save" @click="addAirSpaceComfirm(airSpaceRef)">{{ $t('airspaceAdd.determine') }}</el-button>
      </div>
      <div v-else>
        <el-button class="btn delete" v-if="enterType" @click="goBack">{{ $t('airspaceAdd.return') }}</el-button>
      </div>
    </div>
    <el-dialog
        v-model="dialogVisible"
        title=""
        width="26%"
        :show-close="true"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        center
        top="1vh"
    >
      <img src="@/assets/images/prohibit.png" alt="" />
      <template #footer>
        <div class="dialog-footer">
          <div style="margin-bottom: 30px;font-size: 14px;color: #333333;">
            <span>{{ $t('airspaceAdd.determineDeactivate') }}</span>
            <span style="color: rgba(255, 195, 0, 1)">{{ queryParams.airspaceName }}</span>
            <span>{{ $t('airspaceAdd.doubt') }}</span>
          </div>
          <el-button @click="dialogVisibleFun(0)">{{ $t('airspaceAdd.cancellation') }}</el-button>
          <el-button style="background: #2BC17B; color: #FFFFFF" @click="dialogVisibleFun(1)">
            {{ $t('airspaceAdd.determine') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import $t from "@/i18n/locales/i18n"
export default {
  beforeRouteEnter(to, from, next) {
    const { openType } = to.query;
    if (openType === "add") to.meta.title = "新建空域";
    if (openType === "edit") to.meta.title = "编辑空域";
    if (openType === "detail") to.meta.title = "空域详情";
    next();
  },
}
</script>
<script setup>
import {onMounted, ref, reactive, toRefs, watch, watchEffect, onUnmounted, onBeforeMount, computed} from "vue";
import {ElFormItem, ElInput, ElMessage} from "element-plus"
import { getAirspaceType, settingsAdd, upload, settingsEdit, getDetailInfo } from "@/api/airSpace/airSpaceSetUp";
import { useRouter, useRoute } from "vue-router";
import {getToken} from "@/utils/auth";
// import Upload from "@/components/Upload/index.vue";
import Upload from "@/components/Upload/index";
import {Search} from "@element-plus/icons-vue";
import { getCurrentInstance } from "vue";
const { $t } = getCurrentInstance().proxy;
const route = useRoute();
const router = useRouter();
const dialogVisible = ref(false);
const radioVisible = ref(false);
const airSpaceRef = ref();
const circleVisible = ref(false);
const polygonVisible = ref(false);
const { proxy } = getCurrentInstance();
const airspaceTypeList = ref([]);
const timeStanding = ref("");
const fullColor = ref("");
const lineColor = ref("");
// const airspaceStatus = ref("");
const lonAndLat = ref([]);
const fileList = ref([]);
const layerSwitch = ref(false);
const airspaceId = ref("");
const openType = ref("");
const enterType = ref(false);
const editStatus = ref(false); // false-新增 true-编辑
const disVisible = ref(false);
const editDetermine = ref(false);
const pointLocation = ref("");
const defaultTime = new Date(2000, 1, 1, 23, 59, 59);
const data = reactive({
  queryParams: {
    airspaceName: "",
    airTypeId: "",
    lowHeight: null,
    topHeight: null,
    airSpaceStartTime: "",
    startTime: "",
    endTime: "",
    remark: "",
    files: [],
    pointLocation: "", //空域为圆-存一个中心点 空域为多边形-存多个点位信息
    circle: "", //是否为圆
    radius: null, //半径
    resource: "",
    status: null,
    airspaceStatus: null
  },
  queryRules: {
    airspaceName: [{ required: true, message: "请输入空域名称", trigger: "blur" }],
    airTypeId: [{ required: true, message: "请选择空域类型", trigger: "change" }],
    lowHeight: [
      { required: true, message: "请输入空域底高", trigger: "blur" },
      {
        pattern: /^(([1-9][0-9]{0,3})|0|10000)$/,
        message: '空域底高必须为0-10000之间的整数',
        trigger: 'blur'
      }
    ],
    topHeight: [
      { required: true, message: "请输入空域顶高", trigger: "blur" },
      {
        pattern: /^(([1-9][0-9]{0,3})|0|10000)$/,
        message: '空域顶高必须为0-10000之间的整数',
        trigger: 'blur'
      }
    ],
    airSpaceStartTime: [{ required: true, message: "请选择开始时间", trigger: "change" }],
    endTime: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if (radioVisible.value == false && value == "") {
            callback(new Error("请选择结束时间"));
          } else {
            callback();
          }
        },
        trigger: "change"
      }
    ],
    files: [
      {
        required: true,
        validator: (rule, value, callback) => {
          if (Object.keys(value).length == 0) {
            callback(new Error("请上传文件"));
          } else {
            callback();
          }
        },
        trigger: "change",
      }
    ],
    resource: [{ required: true, message: "请选择绘制空域范围", trigger: "change" }],
    airspaceStatus: [{ required: true, message: "请选择空域状态", trigger: "change" }],
  },
  airSpaceStatusList: [
    {
      label: "启用",
      value: 6
    },
    {
      label: "停用",
      value: 2
    }
  ]
})

const { queryParams, queryRules, airSpaceStatusList } = toRefs(data);

// ---------------------------------------------- 初始化地图  -----------------------------------------------------
let aMap = null;
let auto = ref(null);
let placeSearch = ref(null);
let dataPoi = reactive({});

const initMap = () => {
  aMap = new AMap.Map("airspaceMap", {
    viewMode: "3D",
    zoom: 12,
    center: [120.209947, 30.245853],
    mapStyle: "amap://styles/fresh",
    resizeEnable: true,
  })

  // 禁止地图拖拽 缩放
  // aMap.setStatus({
  //   zoomEnable:false,
  //   dragEnable: false,
  // });

  // 点击获取地图上的经纬度
  // aMap.on('click', function(e) {
  //   document.getElementById("airspaceMap").value = e.lnglat.getLng() + ',' + e.lnglat.getLat()
  //   let lonLat = [e.lnglat.getLng() + ',' + e.lnglat.getLat()];
  //   lonAndLat.value = lonLat.toString().split(",");
  //   if (enterType.value == false && circleStatus == true) {
  //     proxy.$modal.msgSuccess("已获取中心点位置!");
  //   }
  // });

  //输入提示
  const autoOptions = {
    input: "tipinput",
  };

  AMap.plugin(["AMap.PlaceSearch", "AMap.AutoComplete"], function () {
    auto = new AMap.AutoComplete(autoOptions);
    placeSearch = new AMap.PlaceSearch({
      map: aMap,
    }); //构造地点查询类
    auto.on("select", select); //注册监听，当选中某条记录时会触发
    function select(e) {
      dataPoi = e.poi;
    }
  });
}

function mapSelect() {
  placeSearch.setCity(dataPoi.adcode);
  placeSearch.search(dataPoi.name); //关键字查询查询
};

// 构造官方卫星、路网图层
var satelliteLayer = new AMap.TileLayer.Satellite();

// 图层切换
function airspaceControl() {
  if (layerSwitch.value == false) {
    aMap.add(satelliteLayer);
    layerSwitch.value = true;
  }else {
    aMap.remove(satelliteLayer);
    layerSwitch.value = false;
  }
}

function airspaceMouseover() {
  document.getElementById("airspaceControl").title = $t("airspaceSetup.switchMap");
}

function showInfoClick(e) {
  if (circle != null) {
    clearCircle();
  }
  if (circleEditor != null) {
    clearCircleEditor();
  }
  document.getElementById("airspaceMap").value = e.lnglat.getLng() + ',' + e.lnglat.getLat()
  let lonLat = [e.lnglat.getLng() + ',' + e.lnglat.getLat()];
  lonAndLat.value = lonLat.toString().split(",");
  queryParams.value.pointLocation = lonAndLat.value;
  let [ a, b ] = queryParams.value.pointLocation;
  queryParams.value.pointLocation = a + "," + b;
  circle = new AMap.Circle({
    map: aMap,
    center: openType.value !== 'add' ? pointLocation.value.split(",") : lonAndLat.value,
    radius: openType.value !== 'add' ? queryParams.value.radius : 1000, //半径
    borderWeight: 3,
    strokeColor: lineColor.value,
    strokeOpacity: 1,
    strokeWeight: 6,
    fillOpacity: 0.4,
    strokeStyle: 'dashed',
    strokeDasharray: [10, 10],
    // 线样式还支持 'dashed'
    fillColor: fullColor.value,
    zIndex: 50,
  })
  aMap.add(circle);
  // // 缩放地图到合适的视野级别
  aMap.setFitView([circle])

  if (openType.value !== 'detail') {
    circleEditor = new AMap.CircleEditor(aMap, circle, {
      createOptions: {
        strokeColor: lineColor.value,
        fillColor: fullColor.value
      },
      editOptions: {
        strokeColor: lineColor.value,
        fillColor: fullColor.value
      },
    })

    if (editDetermine.value == true) {
      aMap.plugin(["AMap.CircleEditor"], function () {
        circleEditor.open();
      });
      circleEditor.on('move', function (event) {
        // log.info('触发事件：move')
        queryParams.value.pointLocation = event.lnglat.lng + "," + event.lnglat.lat;
      })
      circleEditor.on('adjust', function (event) {
        // log.info('触发事件：adjust')
        queryParams.value.radius = event.radius
        circleEditor.close();
      })
    }
  }
}

let circle = null;
var mouseTool = null;
var circleEditor = null;
var mouseToolEdit = null;
let circleStatus = false; // 当前绘制状态  true-圆形  false-矩形
var polyEditor = null;
var mouseToolEdit3 = null;

function resourceChange(val) {
  console.log(val);
  if (!lineColor.value || !fullColor.value) {
    ElMessage({
      message: $t('airspaceAdd.changeAirType'),
      type: 'warning',
    })
  }else {
    if (val === $t('airspaceAdd.circle')) {
      queryParams.value.resource = $t('airspaceAdd.circle');
      queryParams.value.circle = 1;
      circleStatus = true;
      if (mouseTool != null) {
        clearMouseTool();
      }
      if (mouseToolEdit != null) {
        clearMouseToolEdit();
      }
      if (enterType.value == false) { // 新增  编辑
        circleVisible.value = true;
        polygonVisible.value = false;
        if (openType.value == 'add'){
          aMap.on('click', showInfoClick);
        }
      }
      if (openType.value !== 'add'){ // 编辑  详情
        circle = new AMap.Circle({
          map: aMap,
          center: openType.value !== 'add' ? pointLocation.value.split(",") : lonAndLat.value,
          radius: openType.value !== 'add' ? queryParams.value.radius : 1000, //半径
          borderWeight: 3,
          strokeColor: lineColor.value,
          strokeOpacity: 1,
          strokeWeight: 6,
          fillOpacity: 0.4,
          strokeStyle: 'dashed',
          strokeDasharray: [10, 10],
          // 线样式还支持 'dashed'
          fillColor: fullColor.value,
          zIndex: 50,
        })
        aMap.add(circle);
        // // 缩放地图到合适的视野级别
        aMap.setFitView([circle])
      }

    }else if (val === $t('airspaceAdd.polygon')) {
      if (circle != null) {
        clearCircle();
      }
      if (circleEditor != null) {
        clearCircleEditor();
      }
      if (mouseTool != null) {
        clearMouseTool();
      }
      if (mouseToolEdit != null) {
        clearMouseToolEdit();
      }
      aMap.off('click', showInfoClick)
      queryParams.value.circle = 0;
      queryParams.value.radius = null;
      queryParams.value.resource = $t('airspaceAdd.polygon');
      circleStatus = false;
      if (enterType.value == false) { // 编辑
        polygonVisible.value = true;
        circleVisible.value = false;
      }
      mouseToolEdit = new AMap.Polygon({
        path: openType.value !== 'add' ? eval('[' + queryParams.value.pointLocation + ']') : [],
        strokeColor: lineColor.value,
        strokeWeight: 6,
        strokeOpacity: 1,
        fillOpacity: 0.4,
        fillColor: fullColor.value,
        strokeStyle: "solid",
        bubble: true
      })
      aMap.add([mouseToolEdit]);
      aMap.setFitView();
      if (editDetermine.value == true) {  // 新增
        // aMap.on('click', function (e) {
        //   aMap.remove([mouseToolEdit]);
        // })
        mouseTool = new AMap.MouseTool(aMap);
        mouseTool.polygon({
          strokeColor: lineColor.value,
          strokeOpacity: 1,
          strokeWeight: 6,
          fillColor: fullColor.value,
          fillOpacity: 0.4,
          strokeStyle: "solid"
        })
        mouseTool.on('draw', function(event) {
          var list = event.obj._opts.path;
          let str = "";
          for (var i = 0; i < list.length; i++) {
            if (str == "") {
              str = "[" + list[i] + "]"
            }else {
              str += "," + "[" + list[i] + "]"
            }
          }
          queryParams.value.pointLocation = str;
          mouseTool.close(true);
          mouseToolEdit3 = new AMap.Polygon({
            path: eval('[' + queryParams.value.pointLocation + ']'),
            strokeColor: lineColor.value,
            strokeWeight: 6,
            strokeOpacity: 1,
            fillOpacity: 0.4,
            fillColor: fullColor.value,
            strokeStyle: "solid",
            zIndex: 50,
            bubble: true
          })
          aMap.add([mouseToolEdit3]);
          aMap.setFitView();
          polyEditor = new AMap.PolygonEditor(aMap, mouseToolEdit3);
          polyEditor.open();
        })
      }
    }else if (val === $t('airspaceAdd.reset')) {
      aMap.off('click', showInfoClick)
      circleVisible.value = false;
      polygonVisible.value = false;
      openType.value = "add";
      queryParams.value.resource = "";
      if (circle != null) {
        clearCircle();
      }
      if (circleEditor != null) {
        clearCircleEditor();
      }
      if (mouseTool != null) {
        clearMouseTool();
      }
      if (mouseToolEdit != null) {
        clearMouseToolEdit();
      }
      if (openType.value !== 'edit') {
        editDetermine.value = true;
      }
      if (polyEditor !== null) {
        polyEditor.close();
        aMap.clearMap();
      }
    }
  }
}

function clearCircle() {
  lonAndLat.value = [];
  // aMap.clearMap();
  queryParams.value.radius = null;
  queryParams.value.pointLocation = "";
  aMap.remove(circle);

}

function clearCircleEditor() {
  lonAndLat.value = [];
  queryParams.value.radius = null;
  queryParams.value.pointLocation = "";
  aMap.remove(circleEditor);
  circleEditor.close(true);
}

function clearMouseTool() {
  mouseTool.close(true);
  queryParams.value.radius = null;
  queryParams.value.pointLocation = "";
}

function clearMouseToolEdit() {
  aMap.remove([mouseToolEdit]);
  queryParams.value.radius = null;
  queryParams.value.pointLocation = "";
}
// ---------------------------------------------- dom交互  -----------------------------------------------------

// 文件上传
function uploadSuccess(response) {
  queryParams.value.files.push(response);
  fileList.value.push(response);
}

// 文件删除
function uploadRemove(index) {
  fileList.value.splice(index, 1);
  queryParams.value.files.splice(index, 1);
}

function getairTypeContent(val) {
  airspaceTypeList.value.map((item) => {
    if (item.airTypeId == val) {
      fullColor.value = item.fullColor;
      lineColor.value = item.lineColor;
    }
  })
}

// 空域类型获取
function getAirspaceTypeList() {
  getAirspaceType().then(response => {
    if (response.code === 200) {
      airspaceTypeList.value = response.data;
    }
  })
}

// 永久有效
const radioHandle = () => {
  if (!enterType.value) {
    radioVisible.value = !radioVisible.value
    if (radioVisible.value == true) {
      queryParams.value.endTime = "";
      disVisible.value = true;
    }else{
      disVisible.value = false;
      queryParams.value.endTime = timeStanding.value;
    }
  }
}

function startTimeHandle(val) {
  queryParams.value.startTime = getTime(val);
}

let lastTime = ""
function endTimeHandle(val) {
  console.log(val)
  if (val != null) {
    timeStanding.value = queryParams.value.endTime;
    queryParams.value.endTime = getTime(val);
    lastTime = getTime(val, true);
  }else {
    timeStanding.value = "";
    queryParams.value.endTime = "";
  }
}

// 格式化日期格式
function getTime(value, type) {
  // 计算日期相关值
  let time = new Date(value);
  let Y = time.getFullYear();
  let M = time.getMonth() + 1;
  let D = time.getDate();
  let h = time.getHours();
  let m = time.getMinutes();
  let s = time.getSeconds();
  // let week = time.getDay();
  if (type == true) {
    return Y + '-' + (M < 10 ? '0' + M : M) + '-' + (D < 10 ? '0' + D : D) + ' ' + (h < 10 ? '0' + h : h) + ':' + (m < 10 ? '0' + m : m) + ':' + (s < 10 ? '0' + s : s);
  }
  return Y + '-' + (M < 10 ? '0' + M : M) + '-' + (D < 10 ? '0' + D : D) + ' ' + (h < 10 ? '0' + h : h) + ':' + (m < 10 ? '0' + m : m);
}

function goBack() {
  // proxy.$router.go(-1);
  queryParams.value = initForm();
  router.push({
    path: "/airspace/airspace-setup",
  });
}

const initForm = () => {
  return {
    airspaceName: "",
    airTypeId: "",
    lowHeight: null,
    topHeight: null,
    airSpaceStartTime: "",
    startTime: "",
    endTime: "",
    remark: "",
    files: [],
    pointLocation: "", //空域为圆-存一个中心点 空域为多边形-存多个点位信息
    circle: "", //是否为圆
    radius: null, //半径
    resource: "",
    status: null,
    airspaceStatus: null
  }
}

var overlays = null;
// 新建/编辑空域
const addAirSpaceComfirm = async (airSpaceRef) => {
  if (!airSpaceRef) return;
  if (!!queryParams.value.lowHeight && !!queryParams.value.topHeight) {
    if (Number(queryParams.value.lowHeight) > Number(queryParams.value.topHeight)) { // 空域底高不得大于空域顶高
      ElMessage.error($t('airspaceAdd.lowNoTop'));
      return;
    } else if (Number(queryParams.value.lowHeight) == Number(queryParams.value.topHeight)) { // 空域底高不得等于空域顶高
      ElMessage.error($t('airspaceAdd.lowNoEqualToTop'));
      return;
    }
  }
  if (!!queryParams.value.startTime && !!queryParams.value.endTime) {
    if (queryParams.value.startTime > queryParams.value.endTime) { // 开始时间不能晚于结束时间
      ElMessage.error($t('airspaceAdd.timeLast'));
      return;
    }else if (queryParams.value.startTime === queryParams.value.endTime) { // 开始时间不能等于结束时间
      ElMessage.error($t('airspaceAdd.timeEqual'));
      return;
    }
  }
  if (!!circleEditor) {  // 如果圆的绘制没有编辑完成在保存的时候强制保存
    circleEditor.close();
  }
  if (!!polyEditor) {
    polyEditor.close();
    overlays = aMap.getAllOverlays('polygon');
    let arr = "";
    overlays.forEach(item => {
      let polygon = item.getPath();
      if (polygon.length > 0) {
        polygon.map(obj => {
          let position = [];
          let str = obj.lng + ',' + obj.lat;
          position.push(str);
          if (arr == "")  arr = "[" + obj.lng + ',' + obj.lat + "]"
          else arr += "," + "[" + obj.lng + ',' + obj.lat + "]"
        })
      }
    })
    queryParams.value.pointLocation = arr;
  }

  let startTime = "";
  if(!!queryParams.value.startTime) {
    startTime = time(queryParams.value.startTime)
  }

  let submitData = {
    ...queryParams.value,
    status: queryParams.value.airspaceStatus,
    pointLocation: queryParams.value.pointLocation,
    circle: queryParams.value.circle,
    files: editStatus.value == true ? queryParams.value.files : fileList.value,
    startTime: startTime,
    endTime: queryParams.value.endTime == "" ? "2999-12-12 23:59:59" : lastTime == "" ? queryParams.value.endTime : lastTime,
    radius: queryParams.value.resource == $t('airspaceAdd.circle') && queryParams.value.radius === null ? 1000 : queryParams.value.radius
  };

  await airSpaceRef.validate((valid, fields) => {
    if (valid) {
      if (queryParams.value.pointLocation.length === 0 ){
        ElMessage.error($t('airspaceAdd.dimensionAirspaceRange'));
      }else {
        if (editStatus.value) {
          submitData = {
            ...submitData,
            airspaceId: airspaceId.value
          }
          settingsEdit(submitData).then(response => {
            if (response.code === 200) {
              ElMessage.success($t('airspaceAdd.updateSuccess'));
              goBack();
            }else {
              ElMessage.error($t('airspaceAdd.updateFail'));
            }
          })
        }else {
          settingsAdd(submitData).then(response => {
            if (response.code === 200) {
              ElMessage.success($t('airspaceAdd.successfully'));
              goBack();
            }else {
              ElMessage.success($t('airspaceAdd.addFail'));
            }
          })
        }
      }
    }else {
      console.log("error submit!", fields);
    }
  })
}

function time(value, type) {
  var time = new Date(value);
  let Y = time.getFullYear();
  let M = time.getMonth() + 1;
  let D = time.getDate();
  let h = time.getHours();
  let m = time.getMinutes();
  let s = time.getSeconds();
  // let week = time.getDay();
  return Y + '-' + (M < 10 ? '0' + M : M) + '-' + (D < 10 ? '0' + D : D) + ' ' + (h < 10 ? '0' + h : h) + ':' + (m < 10 ? '0' + m : m) + ':' + (s < 10 ? '0' + s : s);
}

function dialogVisibleChange() {
  if (queryParams.value.airspaceStatus === 2) {
    dialogVisible.value = true
  }else {
    queryParams.value.status = queryParams.value.airspaceStatus
  }
}

function dialogVisibleFun(type) {
  if (type === 0) {
    queryParams.value.airspaceStatus = 6;
    queryParams.value.status = 6;
    // airspaceStatus.value = 6;
  }else if (type === 1) {
    queryParams.value.airspaceStatus = 2;
    queryParams.value.status = 2;
  }
  dialogVisible.value = false;
}

// --------------------------------------------------- 编辑 --------------------------------------------------------\\


onBeforeMount(() => {
  // watch(() => route, (to, from) => {
  //   console.log("route", to, from)
  //   // 监听路由的变化，在路由变化时执行相应逻辑
  // });
  airspaceId.value = route.query.airspaceId;
  openType.value = route.query.openType;
  enterType.value = route.query.enterType == 0 ? true : false;  // true--详情  false--编辑
});

onMounted(() => {
  initMap();
  getAirspaceTypeList();
  if (airspaceId.value) {
    editDetermine.value = false;
    editStatus.value = true; // 编辑
    getDetailInfo(airspaceId.value).then(res => {
      if (res.code == 200) {
        queryParams.value = res.data;
        queryParams.value.airSpaceStartTime = res.data.startTime;
        queryParams.value.airspaceStatus = res.data.status === 2 ? 2 : 6;
        fullColor.value = queryParams.value.fullColor;
        lineColor.value = queryParams.value.lineColor;
        queryParams.value.circle === 0 ? queryParams.value.resource = $t('airspaceAdd.polygon') : queryParams.value.resource = $t('airspaceAdd.circle');
        if (queryParams.value.endTime === "2999-12-12 23:59:59") {
          queryParams.value.endTime = "";
          disVisible.value = true;
          radioVisible.value = true;
        }
        pointLocation.value = queryParams.value.pointLocation;
        resourceChange(queryParams.value.circle === 0 ? $t('airspaceAdd.polygon') : $t('airspaceAdd.circle'))
        // queryParams.value.pointLocation = queryParams.value.pointLocation.split(",")
      }
    })
  }else{
    editStatus.value = false; // 新增
    editDetermine.value = true;
  }
})

onUnmounted(() => {
  aMap.destroy();
});

</script>
<style lang="scss" scoped>
.container{
  //border: 1px red solid;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 0 20px 20px 20px;

  .up-container{
    width: 100%;
    height: 95%;
    margin-bottom: 20px;

    .el-form{
      display: flex;
      justify-content: space-between;
      height: 100%;
    }

    .basic-container {
      width: 26%;
      height: 99%;
      border-radius: 4px;
      background: #FFFFFF;
      padding: 30px;
      overflow: hidden;
      overflow-y: auto;

      .permanent {
        width: auto;
        height: 24px;
        padding: 0;
        position: absolute;
        top: 70%;
        left: -43%;
        color: #999999;
        display: flex;
        justify-content: space-around;
        align-items: center;
        cursor: pointer;
      }

      .permanentRadio {
        width: 14px;
        height: 14px;
        background: url("@/assets/images/rightBox.png");
        background-size: 100% 100%;
      }

      .permanentRadio2 {
        width: 14px;
        height: 14px;
        background: url("@/assets/images/circleBox.png");
        background-size: 100% 100%;
      }

      .createBtn {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px 26px;
        width: 98px;
        height: 36px;
        font-size: 12px;
        box-sizing: border-box;
        border-radius: 4px;
        color: rgba(43, 193, 123, 1);
        background: rgba(51, 151, 255, 0.03);
        border: 1px solid rgba(43, 193, 123, 1);
        cursor: pointer;

        &:hover {
          background: rgba(51, 151, 255, 0.1);
        }
      }

      .title {
        font-size: 16px;
        display: flex;
        align-items: center;
        margin-bottom: 30px;

        img {
          margin-right: 10px;
        }
      }

      :deep .el-form-item__label {
        width: 40%;
        font-size: 14px;
        color: #666666;
        font-weight: 400;
        text-align: right;
      }

      :deep .el-form-item--default {
        margin-bottom: 20px;
      }

      :deep .el-input,
      .el-textarea {
        width: 100%;
        height: 36px;
      }

      :deep .el-select {
        width: 100%;
        height: 36px;
      }

      :deep .el-textarea__inner {
        height: 100%;
        resize: none;
      }
    }
    .draw-container{
      //border: 1px red solid;
      width: 73%;
      height: 99%;
      border-radius: 4px;
      background: #FFFFFF;
      box-sizing: border-box;
      position: relative;
      overflow: hidden;

      .range{
        //border: 1px red solid;
        height: 16%;
        padding: 30px;

        .title{
          font-size: 16px;
          display: flex;
          align-items: center;
          margin-bottom: 10px;
          img{
            margin-right: 10px;
          }
        }
      }

      #airspaceMap{
        width: 100%;
        height: calc(100% - 120px);
      }

      #myPageTop {
        width: 370px;
        height: 40px;
        top: 6%;
        right: 2%;
        position: absolute;
        display: flex;

        input {
          width: 270px;
          height: 40px;
          opacity: 1;
          margin-right: 20px;
          padding: 0 10px;
          border-radius: 4px;
          background: rgba(255, 255, 255, 1);
          border: 1px solid rgba(220, 223, 230, 1);
        }

        .el-button {
          width: 80px;
          height: 40px;
          opacity: 1;
          border-radius: 4px;
          background: rgba(43, 193, 123, 1);
          color: #ffffff;
        }
      }

      .airspaceLayer {
        position: relative;
        width: 30px;
        height: 30px;
        background: url(@/assets/images/airspacePop.png);
        background-size: 100% 100%;
        left: 96%;
        bottom: 28%;
      }

      .airspaceLayer-down {
        position: relative;
        width: 30px;
        height: 30px;
        background: url(@/assets/images/airspacePop.png);
        background-size: 100% 100%;
        left: 96%;
        bottom: 6%;
      }

      .circleDraw{
        width: 24%;
        height: 23%;
        position: relative;
        z-index: 999;
        bottom: 27%;
        left: 76%;
        background-color: #ffffff;
        padding: 13px 5px 6px 20px;
        font-size: 12px;
        color: #999999;
        line-height: 1.5;
      }

      .polygonDraw{
        width: 24%;
        height: 23%;
        position: relative;
        z-index: 999;
        left: 76%;
        bottom: 27%;
        background-color: #ffffff;
        padding: 13px 5px 6px 20px;
        font-size: 12px;
        color: #999999;
      }

    }
  }
  .down-container{
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    right: 20px;
    top: 5px;
    height: 40px;

    :deep .el-button>span {
      display: inline-flex;
      align-items: center;
      font-size: 16px;
      font-weight: 400;
    }

    .btn {
      width: 81px;
      height: 32px;
      line-height: 32px;
      text-align: center;
      border-radius: 4px;
      color: #fff;
      background: rgba(43, 193, 123, 1);
      cursor: pointer;
      &:hover {
        background: rgba(43, 193, 123, 0.85);
      }
    }

    .btn.delete {
      color: rgba(102, 102, 102, 1);
      background: #fff;
      border: 1px solid rgba(220, 223, 230, 1);
      &:hover {
        background: rgba(0, 0, 0, 0.05);
      }
    }
    .btn.save {
      margin-left: 20px;
    }
  }
}

:deep .el-dialog:not(.is-fullscreen) {
  margin-top: 36vh !important;
}
:deep .el-dialog__body{
  text-align: center;
  display: flex;
  justify-content: center;
  padding: 0px calc(var(--el-dialog-padding-primary) + 5px) 20px !important;
}
:deep .el-dialog__footer{
  padding-top: 0;
}

.dialog-footer{
  :deep .el-button:nth-child(1){
    border-color: #EDEDED;
  }
  :deep .el-button{
    width: 81px;
    height: 32px;
    font-size: 12px;
  }
}

</style>